import { app, BrowserWindow, ipcMain } from 'electron'
import path from 'path'
import { readDir } from './readDir'
import { getElectronVersion } from './version'
import initDatabase from './db/dbHelper'
import { UserManager } from './dao/userDao'
import { WsManager } from './dao/wsDao'
import { Window } from './window' // 具体方法放在此处
import { Worker } from 'worker_threads'
import { WsConfigHandler } from './handlers/WsConfigHandler'

const isDevelopment = process.env.NODE_ENV !== 'production'
let worker, window

// 创建主窗口
async function createWindow() {
  window = new Window()
  window.listen() // 设置监听事件，比如主进程与渲染进程之间的通信事件
  window.createWindows({ isMainWin: true }) // 创建窗口，默认为主窗口
  window.createTray() // 创建系统托盘
}

// 关闭所有窗口
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// 准备完成，初始化窗口等操作
app.on('ready', async () => {
  await createWindow()
  // 初始化数据库
  await initDatabase()
  console.log('NODE_ENV :', process.env.NODE_ENV)
  // 创建一个工作线程
  const jsWebsocketFile = path.resolve(path.join(__dirname, '../../workers/websocketServer.cjs'))
  // 从数据库中获取ws配置
  const wsConfig = await WsManager.getInstance().getAll()
  const { host, port } = JSON.parse(wsConfig)[0]
  new Worker(jsWebsocketFile, {
    workerData: { host: host, port: port }
  }).on('message', (msg) => {
    // console.log('websocket message:', msg)
    // 获取所有窗口或特定窗口
    const windows = BrowserWindow.getAllWindows()
    windows.forEach((win) => {
      win.webContents.send('websocket', msg)
    })
  })

  const jsFile = path.resolve(path.join(__dirname, '../../workers/worker.cjs'))
  worker = new Worker(jsFile, {
    workerData: { data: 'worker' }
  })
})

// 根据环境处理不同操作
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

ipcMain.on('readDir', readDir)
// 获取electron版本
ipcMain.handle('getElectronVersion', getElectronVersion)
// 退出系统
ipcMain.handle('exitSystem', () => {
  app.exit()
})

ipcMain.handle('getAllUser', UserManager.getInstance().getAll)

//测试工作线程与渲染进程通信
ipcMain.handle('worker', (event, arg) => {
  console.log('from renderer message:', arg)
  // 向工作线程发送消息
  worker.postMessage(arg)
  return new Promise((resolve, reject) => {
    // 监听工作线程发送的消息并返回给渲染进程用.noce 而不是用.on,否则监听会持续增加
    worker.once('message', (msg) => {
      resolve(msg)
    })
  })
})

//注册处理获取和更新WebSocket配置的IPC消息
new WsConfigHandler(ipcMain, WsManager.getInstance())
